<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px"
    >
      <el-form-item label="应用信息" prop="app_id">
        <el-select
          v-model="queryParams.app_id"
          placeholder="请选择应用信息"
        >
          <el-option
            v-for="item in appOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会员名称" prop="customer_name">
        <el-input
          v-model="queryParams.customer_name"
          placeholder="请输入会员名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="精确会员名称" prop="customer_exact_name">
        <el-input
          v-model="queryParams.customer_exact_name"
          placeholder="请输入精确会员名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="customer_phone">
        <el-input
          v-model="queryParams.customer_phone"
          placeholder="请输入手机号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="网络" prop="network">
        <el-select
          v-model="queryParams.network"
          placeholder="网络"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.wallet_network"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="registerTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary" icon="el-icon-search" size="mini"
          v-hasPermi="['customer:wallet:query']" @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" @sort-change="sortChange">
      <el-table-column sortable="custom" label="钱包编号" align="center" prop="id"/>
      <el-table-column label="会员id" align="center" prop="customer_id" :show-overflow-tooltip="true"/>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="refreshBalance(scope.row)"
            v-hasPermi="['customer:wallet:query']"
          >查询余额
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="refreshDeposit(scope.row)"
            v-hasPermi="['customer:wallet:query']"
          >刷新充值
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="hashRefreshDeposit(scope.row)"
            v-hasPermi="['customer:wallet:query']"
          >刷新充值hash
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="active(scope.row,1)"
            v-if="(scope.row.status == 1 || scope.row.status == 3)  && scope.row.network == 1"
            v-hasPermi="['customer:wallet:active']"
          >trx激活账户
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gather(scope.row,1,1)"
            v-if="scope.row.status !== 0 && scope.row.network == 1"
            v-hasPermi="['customer:wallet:gather']"
          >TRC20-USDT资金归集
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gather(scope.row,2,1)"
            v-if="scope.row.status !== 0 && scope.row.network == 1"
            v-hasPermi="['customer:wallet:gather']"
          >TRC20-TRX资金归集
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gather(scope.row,1,2)"
            v-if="scope.row.status !== 0 && scope.row.network == 2"
            v-hasPermi="['customer:wallet:gather']"
          >ERC20-USDT资金归集
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gather(scope.row,3,2)"
            v-if="scope.row.status !== 0 && scope.row.network == 2"
            v-hasPermi="['customer:wallet:gather']"
          >ERC20-ETH资金归集
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="active(scope.row,3)"
            v-if="(scope.row.status == 1 || scope.row.status == 3) && scope.row.network == 3"
            v-hasPermi="['customer:wallet:active']"
          >bnb激活账户
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gather(scope.row,1,3)"
            v-if="scope.row.status !== 0 && scope.row.network == 3"
            v-hasPermi="['customer:wallet:gather']"
          >BEP20-USDT资金归集
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="gather(scope.row,4,3)"
            v-if="scope.row.status !== 0 && scope.row.network == 3"
            v-hasPermi="['customer:wallet:gather']"
          >BEP20-BNB资金归集
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="会员名称" align="center" key="name" prop="name"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="会员手机号" align="center" key="phone" prop="phone"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="一级代理" align="center" key="first_agent_name" prop="first_agent_name"
                       :show-overflow-tooltip="true" width="160"
      />
      <el-table-column label="注册时间" align="center" key="register_time" prop="register_time" width="160"/>
      <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true"/>
      <el-table-column sortable="custom" label="USDT" align="center" prop="amount" :show-overflow-tooltip="true"/>
      <el-table-column sortable="custom" label="ETH" align="center" prop="eth_amount" :show-overflow-tooltip="true"/>
      <el-table-column sortable="custom" label="TRX" align="center" prop="trx_amount" :show-overflow-tooltip="true"/>
      <el-table-column sortable="custom" label="BNB" align="center" prop="bnb_amount" :show-overflow-tooltip="true"/>
      <el-table-column label="最小金额" align="center" prop="limit_min_amount" :show-overflow-tooltip="true"/>
      <el-table-column label="最大金额" align="center" prop="limit_max_amount" :show-overflow-tooltip="true"/>
      <el-table-column label="网络" align="center" prop="network">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wallet_network" :value="scope.row.network"/>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_wallet_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_wallet_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />

    <el-dialog :title="gatherTitle" :visible.sync="gatherOpen" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="gatherForm" :model="gatherForm" :rules="rules" label-width="80px">
        <span style="color: red"
              v-if="gatherForm.gather_type == 1">自助转账trx归集:由支付地址或者代理地址转账30trx然后归集</span>
        <span style="color: red" v-if="gatherForm.gather_type == 2">直接归集:TRC20-USDT需支付账号转账2trx，如果有开启自动归集则自动租赁能量，手动充值会员手续费，包括trx、带宽、能量</span>
        <span style="color: red"
              v-if="gatherForm.gather_type == 3">代理能量归集:代理地址需要质押trx才能租赁能量给会员地址</span>
        <el-form-item label="归集类型" prop="gather_type">
          <el-radio-group v-model="gatherForm.gather_type">
            <el-radio
              v-for="dict in dict.type.gather_type"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收款钱包" prop="tenant_income_wallet_id">
          <el-select
            v-model="gatherForm.tenant_income_wallet_id"
            placeholder="请选择收款钱包"
            style="width:100%"
          >
            <el-option
              v-for="item in incomeOptions"
              :key="item.id"
              :label="item.address"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="激活钱包" prop="tenant_pay_wallet_id" v-if="gatherForm.gather_type==2">
          <el-select
            v-model="gatherForm.tenant_pay_wallet_id"
            placeholder="请选择激活钱包"
            style="width:100%"
          >
            <el-option
              v-for="item in activeOptions"
              :key="item.id"
              :label="item.address"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input type="number" step="0.01" v-model="gatherForm.amount" placeholder="请输入金额"></el-input>
        </el-form-item>
        <el-form-item label="手续费" prop="fee" v-if="gatherForm.network === 2 && gatherForm.ccy === 1">
          <el-input type="number" step="0.01" v-model="gatherForm.fee" placeholder="请输入手续费"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="google_code">
          <el-input v-model="gatherForm.google_code" placeholder="请输入验证码" maxlength="30"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGatherForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="activeTitle" :visible.sync="activeOpen" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="activeForm" :model="activeForm" :rules="rules" label-width="80px">
        <span style="color: red">激活钱包后才能正常资金归集,支付钱包会支付2.0trx进行激活</span>
        <el-form-item label="激活钱包" prop="tenant_pay_wallet_id">
          <el-select
            v-model="activeForm.tenant_pay_wallet_id"
            placeholder="请选择激活钱包"
            style="width:100%"
          >
            <el-option
              v-for="item in activeOptions"
              :key="item.id"
              :label="item.address"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="验证码" prop="google_code">
          <el-input v-model="activeForm.google_code" placeholder="请输入验证码" maxlength="30"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitActiveForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="refreshDepositTitle" :visible.sync="refreshDepositOpen" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="refreshDepositForm" :model="refreshDepositForm" :rules="rules" label-width="80px">
        <el-form-item label="币种" prop="ccy">
          <el-select
            v-model="refreshDepositForm.ccy"
            placeholder="请输入币种"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.wallet_ccy"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="hash" prop="hash">
          <el-input v-model="refreshDepositForm.hash" placeholder="请输入hash"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="refreshDepositSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  active,
  gatherAll,
  hashRefreshDeposit,
  listCustomerWallet,
  refreshBalance,
  refreshDeposit
} from '@/api/customer/customerWallet'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getGroupApp} from "@/api/metadata/app";
import {getActiveList, getIncomeList} from "@/api/tenant/tenantWallet";

export default {
  name: 'CustomerWallet',
  dicts: ['wallet_network', 'customer_wallet_type', 'customer_wallet_status', 'gather_type', 'wallet_ccy'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台租户钱包表格数据
      dataList: null,
      // 弹出层标题
      gatherTitle: '',
      activeTitle: '',
      refreshDepositTitle: '',
      // 是否显示弹出层
      gatherOpen: false,
      activeOpen: false,
      refreshDepositOpen: false,
      // 日期范围
      registerTimeRange: [],
      // 应用信息
      appOptions: [],
      activeOptions: [],
      incomeOptions: [],
      admin: false,
      // 表单参数
      gatherForm: {},
      activeForm: {},
      refreshDepositForm: {},
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        customer_id: undefined,
        app_id: undefined,
        customer_name: undefined,
        customer_exact_name: undefined,
        customer_phone: undefined,
        customer_email: undefined,
        address: undefined,
        sort_list: [],
        network: 1,
      },
      // 表单校验
      rules: {
        tenant_pay_wallet_id: [
          {required: true, message: '支付钱包不能为空', trigger: 'blur'}
        ],
        tenant_income_wallet_id: [
          {required: true, message: '收款不能为空', trigger: 'blur'}
        ],
        amount: [
          {required: true, message: '金额不能为空', trigger: 'blur'}
        ],
        fee: [
          {required: true, message: '手续费不能为空', trigger: 'blur'}
        ],
        google_code: [
          {required: true, message: '验证码不能为空', trigger: 'blur'}
        ],
        hash: [
          {required: true, message: '交易hash不能为空', trigger: 'blur'}
        ],
        ccy: [
          {required: true, message: '币种不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    // 默认id排序
    this.queryParams.sort_list = [{sort_by: 'id', sort_type: 2}]
    this.getGroupApp()
  },
  methods: {
    sortChange(column) {
      if (column) {
        if (column.order === 'ascending') {
          this.queryParams.sort_list = [{sort_by: column.prop, sort_type: 1}]
        } else if (column.order === 'descending') {
          this.queryParams.sort_list = [{sort_by: column.prop, sort_type: 2}]
        }
        this.getList()
      }
    },
    getGroupApp() {
      getGroupApp().then(response => {
        this.queryParams.type = 1
        this.appOptions = response.data
        this.queryParams.app_id = response.data[0].id
        this.getList()
      })
    },
    getActiveList(appId, network) {
      getActiveList(appId, network).then(response => {
        this.activeOptions = response.data
      })
    },
    getIncomeList(appId, network) {
      getIncomeList(appId, network).then(response => {
        this.incomeOptions = response.data
      })
    },
    /** 查询平台租户钱包列表 */
    getList() {
      this.loading = true
      listCustomerWallet(this.addDateRange(this.queryParams, this.registerTimeRange, '_register_time')).then(response => {
          this.dataList = response.data
          this.total = response.total
          this.loading = false
        }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.gatherOpen = false
      this.activeOpen = false
      this.refreshDepositOpen = false
      this.gatherReset()
      this.activeReset()
      this.refreshDepositReset()
      this.getList()
    },
    // 资金归集表单重置
    gatherReset() {
      this.gatherForm = {
        gather_type: 2,
        fee: undefined,
        customer_wallet_id: undefined,
        amount: undefined,
        tenant_pay_wallet_id: undefined,
        tenant_income_wallet_id: undefined,
        google_code: undefined
      }
      this.resetForm('gatherForm')
    },
    // 账户激活表单重置
    activeReset() {
      this.gatherForm = {
        customer_wallet_id: undefined,
        tenant_pay_wallet_id: undefined,
        google_code: undefined
      }
      this.resetForm('activeForm')
    },
    // 账户激活表单重置
    refreshDepositReset() {
      this.refreshDepositForm = {
        hash: undefined,
        ccy: undefined,
        id: undefined
      }
      this.resetForm('refreshDepositForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.registerTimeRange = []
      let appId = this.queryParams.app_id
      this.resetForm('queryForm')
      this.queryParams.app_id = appId
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 归集操作 */
    gather(row, ccy, network) {
      this.gatherReset()
      this.getActiveList(this.queryParams.app_id, network)
      this.getIncomeList(this.queryParams.app_id, network)
      const id = row.id || this.ids
      this.gatherForm.customer_wallet_id = id
      this.gatherForm.ccy = ccy
      this.gatherForm.network = network
      this.gatherOpen = true
      this.gatherTitle = '资金归集'
    },
    /** 激活账户 */
    active(row, network) {
      this.activeReset()
      this.getActiveList(this.queryParams.app_id, network)
      const id = row.id || this.ids
      this.activeForm.customer_wallet_id = id
      this.activeOpen = true
      this.activeTitle = '激活账户'
    },
    /** 刷新充值 */
    refreshDeposit(row) {
      const id = row.id || this.ids
      refreshDeposit(id).then(response => {
        this.$modal.msgSuccess('刷新成功')
        this.getList()
      })
    },
    /** 刷新充值hash */
    hashRefreshDeposit(row) {
      this.refreshDepositReset()

      const id = row.id || this.ids
      this.refreshDepositForm.id = id
      this.refreshDepositOpen = true
      this.refreshDepositTitle = '刷新充值hash'
    },
    /** 查询余额 */
    refreshBalance(row) {
      const id = row.id || this.ids
      refreshBalance(id).then(response => {
        this.$modal.msgSuccess('查询成功')
        this.getList()
      })
    },
    /** 提交按钮 */
    submitActiveForm: function () {
      this.$refs['activeForm'].validate(valid => {
        if (valid) {
          let step = async () => {
            active(this.activeForm).then(response => {
              this.$modal.msgSuccess('激活成功')
              this.activeOpen = false
              this.getList()
            })
          }
          step()
        }
      })
    },
    /** 提交按钮 */
    submitGatherForm: function () {
      this.$refs['gatherForm'].validate(valid => {
        if (valid) {
          let step = async () => {
            gatherAll(this.gatherForm).then(response => {
              this.$modal.msgSuccess('归集成功')
              this.gatherOpen = false
              this.getList()
            })
          }
          step()
        }
      })
    },
    /** 提交按钮 */
    refreshDepositSubmit: function () {
      this.$refs['refreshDepositForm'].validate(valid => {
        if (valid) {
          let step = async () => {
            hashRefreshDeposit(this.refreshDepositForm).then(response => {
              this.$modal.msgSuccess('刷新充值成功')
              this.refreshDepositOpen = false
              this.getList()
            })
          }
          step()
        }
      })
    }
  }
}
</script>
